package com.sihai.ehr.service.impl;

import com.sihai.core.DataAccessor;
import com.sihai.core.Limit;
import com.sihai.core.LimitedList;
import com.sihai.core.Sorter;
import com.sihai.ehr.model.biz.SalaryStatistics;
import com.sihai.ehr.model.biz.SalaryStatisticsDetail;
import com.sihai.ehr.service.SalaryStatisticsService;
import com.sihai.ehr.utils.ExcelUtils;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang.xwork.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by IntelliJ IDEA.
 * User: Wang.Yi
 * Date: 2013-3-2
 * Time: 13:38:34
 * To change this template use File | Settings | File Templates.
 */
@Service("salaryStatisticsService")
public class SalaryStatisticsServiceImpl implements SalaryStatisticsService{

    @Resource
    private DataAccessor dataAccessor;

    @Override
    public LimitedList<SalaryStatistics> find(int year, int month, Long organizationId, Long dutyId, Sorter sorter, Limit limit) {
        if(organizationId==null){
            return null;
        }
        String hql="from SalaryStatistics st where st.year=? and st.month=? and st.employeeinfoWork.organization.treePath like ? and st.employeeinfoWork.cancel='0' and st.employeeinfoWork.baseId.cancel='0' and st.employeeinfoWork.baseId.state='1'";
        String treePath = "%,"+organizationId.longValue()+",%";
        Object[] args={year,month,treePath};
        if(dutyId!=null && dutyId>0){
            hql+=" and st.employeeinfoWork.duty.id=? ";
            args=new Object[]{year,month,treePath,dutyId};
        }

        return dataAccessor.findByHql(SalaryStatistics.class,hql,args,limit,sorter);  
    }
    
    @Override
    public LimitedList<SalaryStatistics> findByUserId(int year, int month, Long workId, Sorter sorter, Limit limit) {
        if(workId==null){
            return null;
        }
        String hql="from SalaryStatistics st where st.employeeinfoWork.id=?";
        if(year > 0){
        	hql += " and st.year=" + year;
        }
        
        if(month > 0){
        	hql += " and st.month=" + month;
        }
        Object[] args={workId};
        return dataAccessor.findByHql(SalaryStatistics.class,hql,args,limit,sorter);  
    }

    @Override
    public Boolean report(List<SalaryStatistics> statisticses, String saveFile) throws Exception{
        if(statisticses == null || statisticses.isEmpty()){
            return false;
        }
        //薪资架构项目名称列表
        List<String> structureDetails = dataAccessor.findByHql(String.class, "select ssd.schemeTitle from SalaryStructureDetail ssd order by id", null, null, null);
        //自定义薪资框架项目名称列表
        List<String> customDetails = dataAccessor.findByHql(String.class, "select scd.schemeTitle from SalaryCustomDetail scd order by id", null, null, null);
        List<String> details = null;
        if(structureDetails == null || structureDetails.isEmpty()){
            details = customDetails;
        }
        if(customDetails == null || customDetails.isEmpty()){
            details = structureDetails;
        }
        if(structureDetails != null && customDetails != null){
            structureDetails.addAll(customDetails);
            details = structureDetails;
        }

        int detailSize = details.size();

        WritableWorkbook workbook = null;
        try {
            workbook = Workbook.createWorkbook(new File(saveFile));
            WritableSheet ws=workbook.createSheet("薪资福利统计",1);
            //添加title
            ws.addCell(new Label(0,0,"员工工号"));
            ws.addCell(new Label(1,0,"姓名"));
            ws.addCell(new Label(2,0,"部门"));
            ws.addCell(new Label(3,0,"职务"));
            //Label label04=new Label(4,0,"薪资项目");
            for(int i=0; i<detailSize; i++){
                ws.addCell(new Label(4+i, 0, details.get(i)));
            }
            ws.addCell(new Label(4+detailSize, 0, "公司付款"));
            ws.addCell(new Label(5+detailSize, 0, "合计"));
            for(int j = 0; j<statisticses.size(); j++){
                SalaryStatistics s = statisticses.get(j);
                ws.addCell(new Label(0, j+1, s.getEmployeeinfoWork().getWorkNo()));
                ws.addCell(new Label(1, j+1, s.getEmployeeinfoWork().getBaseId().getName()));
                ws.addCell(new Label(2, j+1, s.getEmployeeinfoWork().getOrganization().getFullName()));
                ws.addCell(new Label(3, j+1, s.getEmployeeinfoWork().getDuty().getDutyName()));
                for(int k=0; k<detailSize; k++){
                    ws.addCell(new Label(4+k, j+1, findDetailSalary(details.get(k), s.getDetails())+""));
                }
                ws.addCell(new Label(4+detailSize, j+1, s.getCompanyPaySalary()+""));
                ws.addCell(new Label(5+detailSize, j+1, s.getActaulPaySalary()+""));
            }

            try {
                workbook.write();
                workbook.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
        return true;
    }

    private float findDetailSalary(String schemeTitle, Set<SalaryStatisticsDetail> details){
        if(details == null || details.isEmpty()){
            return 0f;
        }
        for(SalaryStatisticsDetail d : details){
            if(StringUtils.equals(d.getSchemeTitle(), schemeTitle)){
                return d.getSchemeSalary();
            }
        }
        return 0f;
    }
}
